<template>
<el-button @click="goBack" class="goback">返回</el-button>
<el-card style="min-width: 480px" class="main">
    <template #header>
    <div class="card-header">
        <div class="title">发布活动</div>
    </div>
    </template>
    <el-form
    ref="ruleFormRef"
    style="max-width: 400px"
    :model="ruleForm"
    status-icon
    label-width="auto"
    class="demo-ruleForm"
>
    <el-form-item label="活动名称" prop="title" >
    <el-input v-model="ruleForm.title"/>
    </el-form-item>
    <el-form-item label="开始时间" prop="startTime" >
        <el-date-picker
        v-model="ruleForm.startTime"
        type="datetime"
        placeholder="请选择活动开始时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        format="YYYY-MM-DD HH:mm:ss"
      />
    
    </el-form-item>
    <el-form-item label="活动内容" prop="content" >
    <el-input v-model="ruleForm.content" type="textarea" :autosize="{ minRows: 2, maxRows: 40 }"/>
    </el-form-item>
    <el-form-item label="结束时间" prop="endTime" >
        <el-date-picker
        v-model="ruleForm.endTime"
        type="datetime"
        placeholder="请选择活动结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>
    
    <el-form-item label="活动地点" prop="activityPlace" >
    <el-input v-model="ruleForm.activityPlace"/>
    </el-form-item>
    <el-form-item label="需要人数" prop="activityNum" >
    <el-input v-model="ruleForm.activityNum" style="width: 80px;"/>
    </el-form-item>
    <el-form-item label="活动封面" prop="imageUrl" >
        <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.jpeg,.png"
        >
            <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
    </el-form-item>
    </el-form>
    <template #footer>
    
    <el-button type="primary" @click="submitForm" class="fabu">
        发布
    </el-button>
    </template>
</el-card>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from "vue-router";
import {AddActivityAPI} from '../../api/activity'
import type { UploadProps } from 'element-plus'
import useCounter from '../../stores/pinia';
  import { parseJwt } from '../../stores/pinia'

const router=useRouter()
const counterStore=useCounter()
const userInfo=ref({})

const initialFormData  = ref({
    authorId:null,
    imageUrl:"",
    title:"",
    content:"",
    name:"",
    isShow:0,
    activityNum:"",
    startTime:"",
    endTime:"",
    activityPlace:""
});
const ruleForm = ref({...initialFormData.value });
const goBack =()=>{
    // console.log(123);
    
    router.push('/activity')
}


const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
        // console.log(response.data)
        ruleForm.value.imageUrl = response.data
        // console.log(ruleForm.value.imageUrl)
        ElMessage.success('封面上传成功');
    }

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
// console.log(rawFile)
const isCorrectExtension = rawFile.name.endsWith('.jpg') || rawFile.name.endsWith('.png')||rawFile.name.endsWith('.jpeg');
if (!isCorrectExtension) {
    ElMessage.error('只能上传jpg或png格式的图片')
    return false
} else if (rawFile.size / 1024/512 > 1.5) {
    ElMessage.error('图片大小不能超过1MB!')
    return false
}
return true
}
const submitForm=async()=>{
    const requiredFields = ['title', 'content', 'startTime', 'endTime', 'activityPlace', 'activityNum'];
    const missingFields = requiredFields.filter(field =>!ruleForm.value[field]);
    if (missingFields.length > 0) {
        ElMessage.error(`以下字段不能为空: ${missingFields.join(', ')}`);
        return;
    }
    // console.log("修改的活动",ruleForm.value)
    ruleForm.value.authorId=userInfo.value.id
    ruleForm.value.name=userInfo.value.username
    const result = await AddActivityAPI(ruleForm.value)
    // console.log(result.data);
    if(result.data.code === 0){
        ElMessage.success('活动发布成功');
        router.push("/activity")
    // 重置表单数据
    Object.keys(initialFormData).forEach(key => {
        ruleForm.value[key] = initialFormData[key];
      });
    } else if(result.data.code === 1){
      ElMessage.error('活动发布失败，请检查输入信息');
    }    
}
onMounted(()=>{
  const jwt=counterStore.jwt
  userInfo.value=parseJwt(jwt).claims
  // console.log(userInfo.value)
})
</script>
<style scoped>
.goback{
position: fixed;
margin-left: 5%;
margin-top: 50px;
font-size:24px;
color: #474a59;
padding: 0 6px;
font-weight: 500;
border-color: #dbd2d2ac;
border-bottom: 3px solid #dbd2d2ac;
background-color: #dbd2d2ac;
}
.main{
    width: 60%;
    /* height: 90%; */
    background-color: #fff;
    /* display: flex; */
    margin: auto;
    margin-top: 50px;
    /* padding-top: 50px; */
}
.title{
width: 99px;
font-size:24px;
color: #474a59;
padding: 0 6px;
font-weight: 500;
border-color: #dbd2d2ac;
border-bottom: 3px solid #dbd2d2ac;
background-color: #dbd2d2ac;
border-radius: 3px;
}
.avatar-uploader .avatar {
width: 178px;
height: 178px;
display: block;
}
.avatar-uploader{
border: 1px dashed var(--el-border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: var(--el-transition-duration-fast);
}
.el-upload {
border: 1px dashed var(--el-border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: var(--el-transition-duration-fast);
}
.avatar-uploader:hover {
border-color: var(--el-color-primary);
}
.el-upload:hover {
border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
text-align: center;
}
.fabu{
display: block;
margin: auto;
width: 30%;
font-size:24px;
color: #474a59;
padding: 0 6px;
font-weight: 500;
border-color: #dbd2d2ac;
border-bottom: 3px solid #dbd2d2ac;
background-color: #dbd2d2ac;
/* border-radius: 3px; */
}
.demo-ruleForm {
    width: 100%;
  display: grid;
  grid-template-columns: 400px 250px;
  grid-column-gap: 50px;
  grid-row-gap: 10px;
  /* place-items: center; */
  /* margin: 0 auto;
  justify-items: center; */
  /* max-width: 800px;  */
}
</style>